title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How can I find the full path to a font from its display name on a Mac?
469
21
2008-08-02T15:11:16Z
3,040
12
2008-08-06T03:01:23Z
[ "python", "osx", "fonts", "photoshop" ]
I am using the Photoshop's javascript API to find the fonts in a given PSD. Given a font name returned by the API, I want to find the actual physical font file that that font name corresponds to on the disc. This is all happening in a python program running on OSX so I guess I'm looking for one of: * Some Photoshop ...
Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef. Cocoa doesn't have any native support...
Get a preview JPEG of a PDF on Windows?
502
27
2008-08-02T17:01:58Z
536
9
2008-08-02T18:49:07Z
[ "python", "windows", "image", "pdf" ]
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF. On the Mac I am spawning [sips](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/sips.1.html). Is there something similarly simple I can do on Windows?
You can use ImageMagick's convert utility for this, see some examples in [http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html](https://web.archive.org/web/20120413111338/http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html) : > ``` > Convert taxes.pdf taxes.jpg > ``` > > Will...
Get a preview JPEG of a PDF on Windows?
502
27
2008-08-02T17:01:58Z
7,090
25
2008-08-10T08:08:33Z
[ "python", "windows", "image", "pdf" ]
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF. On the Mac I am spawning [sips](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/sips.1.html). Is there something similarly simple I can do on Windows?
ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the `ps:alpha` delegate in ImageMagick, just adjusted to use JPEG as output): ``` gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLast...
Continuous Integration System for a Python Codebase
535
40
2008-08-02T18:43:54Z
538
23
2008-08-02T18:56:56Z
[ "python", "continuous-integration", "extreme-programming" ]
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this...
One possibility is Hudson. It's written in Java, but there's integration with Python projects: > [Hudson embraces Python](http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html) I've never tried it myself, however. (**Update**, Sept. 2011: After a trademark dispute Hudson has been renamed to [Jenkins](http:...
Continuous Integration System for a Python Codebase
535
40
2008-08-02T18:43:54Z
541
20
2008-08-02T19:06:40Z
[ "python", "continuous-integration", "extreme-programming" ]
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this...
We run [Buildbot - Trac](http://buildbot.net/trac) at work, I haven't used it too much since my code base isn't part of the release cycle yet. But we run the tests on different environments (OSX/Linux/Win) and it sends emails --and it's written in python.
Continuous Integration System for a Python Codebase
535
40
2008-08-02T18:43:54Z
660
14
2008-08-03T12:09:18Z
[ "python", "continuous-integration", "extreme-programming" ]
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this...
Second the Buildbot - Trac integration. You can find more information about the integration on the [Buildbot website](http://buildbot.net/trac/wiki/BuildbotAndTrac). At my previous job, we wrote and used the plugin they mention (tracbb). What the plugin does is rewriting all of the Buildbot urls so you can use Buildbot...
Continuous Integration System for a Python Codebase
535
40
2008-08-02T18:43:54Z
61,746
13
2008-09-15T00:11:21Z
[ "python", "continuous-integration", "extreme-programming" ]
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this...
We use both Buildbot and Hudson for Jython development. Both are useful, but have different strengths and weaknesses. Buildbot's configuration is pure Python and quite simple once you get the hang of it (look at the epydoc-generated API docs for the most current info). Buildbot makes it easier to define non-testing ta...
cx_Oracle: How do I iterate over a result set?
594
25
2008-08-03T01:15:08Z
595
25
2008-08-03T01:17:36Z
[ "python", "sql", "database", "oracle", "cx-oracle" ]
There are several ways to iterate over a result set. What are the tradeoff of each?
The canonical way is to use the built-in cursor iterator. ``` curs.execute('select * from people') for row in curs: print row ``` --- You can use `fetchall()` to get all rows at once. ``` for row in curs.fetchall(): print row ``` It can be convenient to use this to create a Python list containing the value...
cx_Oracle: How do I iterate over a result set?
594
25
2008-08-03T01:15:08Z
125,140
17
2008-09-24T02:51:00Z
[ "python", "sql", "database", "oracle", "cx-oracle" ]
There are several ways to iterate over a result set. What are the tradeoff of each?
My preferred way is the cursor iterator, but setting first the arraysize property of the cursor. ``` curs.execute('select * from people') curs.arraysize = 256 for row in curs: print row ``` In this example, cx\_Oracle will fetch rows from Oracle 256 rows at a time, reducing the number of network round trips that ...
Using 'in' to match an attribute of Python objects in an array
683
28
2008-08-03T13:19:16Z
745
8
2008-08-03T15:59:19Z
[ "python", "arrays", "iteration" ]
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, ``` foo in iter_attr(array of python objects, attribute name) ``` I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers
Are you looking to get a list of objects that have a certain attribute? If so, a [list comprehension](http://docs.python.org/tut/node7.html#SECTION007140000000000000000) is the right way to do this. ``` result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')] ```
Using 'in' to match an attribute of Python objects in an array
683
28
2008-08-03T13:19:16Z
57,833
29
2008-09-11T22:42:14Z
[ "python", "arrays", "iteration" ]
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, ``` foo in iter_attr(array of python objects, attribute name) ``` I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers
Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before `in` could start its search. The temporary list can be avoiding by using a generat...
Class views in Django
742
30
2008-08-03T15:55:28Z
4,572
7
2008-08-07T10:44:23Z
[ "python", "django", "views", "oop" ]
[Django](http://www.djangoproject.com/) view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that d...
If you're simply displaying data from models, why not use the [Django Generic Views](https://docs.djangoproject.com/en/1.2/ref/generic-views/)? They're designed to let you easy show data from a model without having to write your own view and stuff about mapping URL paramaters to views, fetching data, handling edge case...
Class views in Django
742
30
2008-08-03T15:55:28Z
33,957
36
2008-08-29T04:29:22Z
[ "python", "django", "views", "oop" ]
[Django](http://www.djangoproject.com/) view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that d...
I've created and used my own generic view classes, defining **`__call__`** so an instance of the class is callable. I really like it; while Django's generic views allow some customization through keyword arguments, OO generic views (if their behavior is split into a number of separate methods) can have much more fine-g...
Class views in Django
742
30
2008-08-03T15:55:28Z
2,921,293
11
2010-05-27T13:02:08Z
[ "python", "django", "views", "oop" ]
[Django](http://www.djangoproject.com/) view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that d...
I needed to use class based views, but I wanted to be able to use the full name of the class in my URLconf without always having to instantiate the view class before using it. What helped me was a surprisingly simple metaclass: ``` class CallableViewClass(type): def __call__(cls, *args, **kwargs): if args ...
Python and MySQL
766
20
2008-08-03T17:44:07Z
1,619
17
2008-08-04T21:54:11Z
[ "python", "mysql", "postgresql", "bpgsql" ]
I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host. I foun...
MySQLdb is what I have used before. If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do ...
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
783
52
2008-08-03T18:40:09Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these gro...
Can you show us your code? The example on the Python docs is quite straightforward: ``` groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) ``` So in your case, data is a list of nodes, keyfunc is where the logic of...
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
7,286
394
2008-08-10T18:45:32Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these gro...
As Sebastjan said, **you first have to sort your data. This is important.** The part I didn't get is that in the example construction ``` groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) ``` `k` is the current groupi...
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
37,252
24
2008-08-31T23:27:16Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these gro...
A neato trick with groupby is to run length encoding in one line: ``` [(c,len(list(cgen))) for c,cgen in groupby(some_string)] ``` will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
14,443,477
15
2013-01-21T16:54:08Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these gro...
Another example: ``` for key, igroup in itertools.groupby(xrange(12), lambda x: x // 5): print key, list(igroup) ``` results in ``` 0 [0, 1, 2, 3, 4] 1 [5, 6, 7, 8, 9] 2 [10, 11] ``` Note that igroup is an iterator (a sub-iterator as the documentation calls it). This is useful for chunking a generator: ``` de...
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
16,427,674
8
2013-05-07T20:09:46Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these gro...
I would like to give another example where groupby without sort is not working. Adapted from example by James Sulak ``` from itertools import groupby things = [("vehicle", "bear"), ("animal", "duck"), ("animal", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda...
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
20,013,133
10
2013-11-16T00:39:31Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these gro...
WARNING: The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so using ``` for x in list(groupby(range(10))): print(list(x[1])) ``` will produce: ``` [] [] [] [] [] [] [] [] [] [9] ``` Instead, of list(groupby(...)), try [(k, list(g)) for k,g in g...
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
982
14
2008-08-04T02:31:13Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** ...
In Python monkey patching generally works by overwriting a class or functions signature with your own. Below is an example from the [Zope Wiki](http://wiki.zope.org/zope2/MonkeyPatch): ``` from SomeOtherProduct.SomeModule import SomeClass def speak(self): return "ook ook eee eee eee!" SomeClass.speak = speak ...
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
2,982
576
2008-08-06T00:33:35Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** ...
In Python, there is a difference between functions and bound methods. ``` >>> def foo(): ... print "foo" ... >>> class A: ... def bar( self ): ... print "bar" ... >>> a = A() >>> foo <function foo at 0x00A98D70> >>> a.bar <bound method A.bar of <__main__.A instance at 0x00A9BC88>> >>> ``` Bound method...
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
959,064
66
2009-06-06T05:31:38Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** ...
Module **new** is deprecated since python 2.6 and removed in 3.0, use **types** see <http://docs.python.org/library/new.html> In the example below I've deliberately removed return value from `patch_me()` function. I think that giving return value may make one believe that patch returns a new object, which is not true...
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
8,961,717
25
2012-01-22T14:20:54Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** ...
I think that the above answers missed the key point. Let's have a class with a method: ``` class A(object): def m(self): pass ``` Now, let's play with it in ipython: ``` In [2]: A.m Out[2]: <unbound method A.m> ``` Ok, so *m()* somehow becomes an unbound method of *A*. But is it really like that? ``` ...
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
16,240,409
7
2013-04-26T15:47:35Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** ...
There are at least two ways for attach a method to an instance without `types.MethodType`: ``` >>> class A: ... def m(self): ... print 'im m, invoked with: ', self >>> a = A() >>> a.m() im m, invoked with: <__main__.A instance at 0x973ec6c> >>> a.m <bound method A.m of <__main__.A instance at 0x973ec6c>> >>> >>>...
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
28,060,251
10
2015-01-21T05:31:23Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** ...
> # Adding a Method to an Existing Object Instance > > I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in python, I think this is called Monkey Patching (or in some cases Duck Punching). I understand that it's not always a good decision to do so. **But, how might o...
How do you express binary literals in Python?
1,476
251
2008-08-04T18:20:36Z
1,484
57
2008-08-04T18:34:45Z
[ "python", "syntax", "binary", "integer", "literals" ]
How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: ``` >>> 0x12AF 4783 >>> 0x100 256 ``` and octal: ``` >>> 01267 695 >>> 0100 64 ``` **How do you use literals to express binary in Python?** --- ***Summary of Answer...
``` >>> print int('01010101111',2) 687 >>> print int('11111111',2) 255 ``` Another way.
How do you express binary literals in Python?
1,476
251
2008-08-04T18:20:36Z
13,107
204
2008-08-16T12:35:36Z
[ "python", "syntax", "binary", "integer", "literals" ]
How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: ``` >>> 0x12AF 4783 >>> 0x100 256 ``` and octal: ``` >>> 01267 695 >>> 0100 64 ``` **How do you use literals to express binary in Python?** --- ***Summary of Answer...
For reference—*future* Python possibilities: Starting with Python 2.6 you can express binary literals using the prefix **0b** or **0B**: ``` >>> 0b101111 47 ``` You can also use the new **bin** function to get the binary representation of a number: ``` >>> bin(173) '0b10101101' ``` Development version of the docu...
Any experiences with Protocol Buffers?
1,734
20
2008-08-05T00:12:55Z
1,780
8
2008-08-05T01:14:30Z
[ "python", "xml", "database", "protocol-buffers" ]
I was just looking through some information about Google's [protocol buffers](http://code.google.com/apis/protocolbuffers/) data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text e...
If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea. Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a publ...
Any experiences with Protocol Buffers?
1,734
20
2008-08-05T00:12:55Z
6,161
10
2008-08-08T17:12:24Z
[ "python", "xml", "database", "protocol-buffers" ]
I was just looking through some information about Google's [protocol buffers](http://code.google.com/apis/protocolbuffers/) data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text e...
Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case. I would also recommend [JSON](http://en.wikipedia.org/wiki/JSON) as being the most compact text-based format.
How do I make a menu that does not require the user to press [enter] to make a selection?
1,829
12
2008-08-05T02:39:23Z
1,840
8
2008-08-05T02:54:54Z
[ "python" ]
I've got a menu in Python. That part was easy. I'm using `raw_input()` to get the selection from the user. The problem is that `raw_input` (and input) require the user to press `Enter` after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far: ``` ...
**On Linux:** * set raw mode * select and read the keystroke * restore normal settings ``` import sys import select import termios import tty def getkey(): old_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) answer = sys.stdin.read(1) t...
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
1,857
341
2008-08-05T03:27:03Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
``` >>> import os >>> print os.name posix >>> import platform >>> platform.system() 'Linux' >>> platform.release() '2.6.22-15-generic' ``` See: [platform — Access to underlying platform’s identifying data](https://docs.python.org/2/library/platform.html)
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
1,871
112
2008-08-05T03:57:22Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista! ``` >>> import os >>> os.name 'nt' >>> import platform >>> platform.system() 'Windows' >>> platform.release() 'Vista' ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
1,879
91
2008-08-05T04:13:53Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
For the record here's the results on Mac: ``` >>> import os >>> os.name 'posix' >>> import platform >>> platform.system() 'Darwin' >>> platform.release() '8.11.1' ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
28,426
30
2008-08-26T15:41:50Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
You can also use sys.platform if you already have imported sys and you don't want to import another module ``` >>> import sys >>> sys.platform 'linux2' ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
553,500
13
2009-02-16T14:43:18Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
I do this ``` import sys print sys.platform ``` Docs here : [sys.platform](http://docs.python.org/library/sys.html#sys.platform). Everything you need is probably in the sys module.
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
3,021,004
7
2010-06-11T07:37:56Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
I am using the WLST tool that comes with weblogic, and it doesn't implement the platform package. ``` wls:/offline> import os wls:/offline> print os.name java wls:/offline> import sys wls:/offline> print sys.platform 'java1.5.0_11' ``` Apart from patching the system *javaos.py* ([issue with os.system() on windows 20...
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
6,477,354
7
2011-06-25T11:10:45Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
``` >>> import platform >>> platform.system() ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
14,477,954
15
2013-01-23T10:55:26Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
A comparison between the different methods, and what they return on different operating systems can be found here: [OS\_flavor\_name\_version](https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version) Methods that are compared: ``` import platform import sys def linux_distribution(): try: return platf...
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
25,863,224
35
2014-09-16T07:42:41Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
Sample code to differentiate OS's using python: ``` from sys import platform as _platform if _platform == "linux" or _platform == "linux2": # linux elif _platform == "darwin": # MAC OS X elif _platform == "win32": # Windows ```
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
31
2008-08-05T07:18:55Z
1,987
19
2008-08-05T07:27:40Z
[ "python", "list", "tuples" ]
In many places, `(1,2,3)` and `[1,2,3]` can be used interchangeably. When should I use one or the other, and why?
The list [1,2,3] is dynamic and flexible but that flexibility comes at a speed cost. The tuple (1,2,3) is fixed (immutable) and therefore faster.
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
31
2008-08-05T07:18:55Z
2,277
26
2008-08-05T13:22:43Z
[ "python", "list", "tuples" ]
In many places, `(1,2,3)` and `[1,2,3]` can be used interchangeably. When should I use one or the other, and why?
From the [Python FAQ](http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types): > Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of ...
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
31
2008-08-05T07:18:55Z
4,595
10
2008-08-07T11:21:56Z
[ "python", "list", "tuples" ]
In many places, `(1,2,3)` and `[1,2,3]` can be used interchangeably. When should I use one or the other, and why?
Tuples are a quick\flexible way to create *composite* data-types. Lists are containers for, well, lists of objects. For example, you would use a List to store a list of student details in a class. Each student detail in that list may be a 3-tuple containing their roll number, name and test score. ``` `[(1,'Mark',86...
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
31
2008-08-05T07:18:55Z
12,557
7
2008-08-15T18:00:37Z
[ "python", "list", "tuples" ]
In many places, `(1,2,3)` and `[1,2,3]` can be used interchangeably. When should I use one or the other, and why?
The notion of tuples are highly expressive: * Pragmatically, they are great for packing and unpacking values (`x,y=coord`). * In combination with dictionaries (hash tables), they allow forms of mapping that would otherwise require many levels of association. For example, consider marking that (x,y) has been found. ...
File size differences after copying a file to a server vía FTP
2,311
26
2008-08-05T13:40:47Z
2,316
14
2008-08-05T13:45:38Z
[ "php", "python", "ftp", "webserver" ]
I have created a PHP-script to update a webserver that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. Once I download ag...
Do you need to open the locfile in binary using `rb`? ``` f = open (locfile, "rb") ```
How can I create a directly-executable cross-platform GUI app using Python?
2,933
171
2008-08-05T22:26:00Z
2,937
189
2008-08-05T22:34:25Z
[ "python", "user-interface", "deployment", "tkinter", "release-management" ]
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the...
First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. **Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)** Of course, there are many, but the most popular that I've seen in wild are: * [T...
How can I create a directly-executable cross-platform GUI app using Python?
2,933
171
2008-08-05T22:26:00Z
12,166
13
2008-08-15T11:56:02Z
[ "python", "user-interface", "deployment", "tkinter", "release-management" ]
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the...
An alternative tool to py2exe is [bbfreeze](http://pypi.python.org/pypi/bbfreeze/) which generates executables for windows and linux. It's newer than py2exe and handles eggs quite well. I've found it magically works better without configuration for a wide variety of applications.
How can I create a directly-executable cross-platform GUI app using Python?
2,933
171
2008-08-05T22:26:00Z
31,859
39
2008-08-28T08:41:45Z
[ "python", "user-interface", "deployment", "tkinter", "release-management" ]
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the...
Another system (not mentioned in the accepted answer yet) is PyInstaller, which worked for a PyQt project of mine when py2exe would not. I found it easier to use. <http://www.pyinstaller.org/> Pyinstaller is based on Gordon McMillan's Python Installer. Which is no longer available.
How can I create a directly-executable cross-platform GUI app using Python?
2,933
171
2008-08-05T22:26:00Z
265,570
7
2008-11-05T15:53:19Z
[ "python", "user-interface", "deployment", "tkinter", "release-management" ]
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the...
There's also [PyGTK](http://pygtk.org/), which is basically a Python wrapper for the Gnome Toolkit. I've found it easier to wrap my mind around than Tkinter, coming from pretty much no knowledge of GUI programming previously. It works pretty well and has some good tutorials. Unfortunately there isn't an installer for P...
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
3,071
925
2008-08-06T03:57:16Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which...
Assuming module `foo` with method `bar`: ``` import foo methodToCall = getattr(foo, 'bar') result = methodToCall() ``` As far as that goes, lines 2 and 3 can be compressed to: ``` result = getattr(foo, 'bar')() ``` if that makes more sense for your use case. You can use `getattr` in this fashion on class instance b...
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
4,605
145
2008-08-07T11:35:23Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which...
Patrick's solution is probably the cleanest. If you need to dynamically pick up the module as well, you can import it like: ``` m = __import__ ('foo') func = getattr(m,'bar') func() ```
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
834,451
266
2009-05-07T12:45:13Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which...
``` locals()["myfunction"]() ``` or ``` globals()["myfunction"]() ``` [locals](http://docs.python.org/library/functions.html#locals) returns a dictionary with a current local symbol table. [globals](http://docs.python.org/library/functions.html#globals) returns a dictionary with global symbol table.
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
9,272,378
12
2012-02-14T05:55:36Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which...
For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this: ``` myFnName = "MyFn" myAppName = "MyApp" app = sys.modules[myAppName] fn = getattr(app,myFnName) ```
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
12,025,554
46
2012-08-19T09:40:43Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which...
Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this: ``` # Get class from globals and create an instance m = globals()['our_class']() # Get the function (from the instance) that we need to call func = getattr(m, 'function_name') # Call it func() ``` ...
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
14,072,943
8
2012-12-28T16:56:45Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which...
none of what was suggested helped me. I did discover this though. ``` <object>.__getattribute__(<string name>)(<params>) ``` I am using python 2.66 Hope this helps
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
19,393,328
39
2013-10-16T00:24:22Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which...
Given a string, with a complete python path to a function, this is how I went about getting the result of said function: ``` import importlib function_string = 'mypackage.mymodule.myfunc' mod_name, func_name = function_string.rsplit('.',1) mod = importlib.import_module(mod_name) func = getattr(mod, func_name) result =...
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
22,959,509
17
2014-04-09T10:17:41Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which...
The answer (I hope) no one ever wanted Eval like behavior ``` getattr(locals().get("foo") or globals().get("foo"), "bar")() ``` Why not add auto-importing ``` getattr( locals().get("foo") or globals().get("foo") or __import__("foo"), "bar")() ``` In case we have extra dictionaries we want to check `...
How to sell Python to a client/boss/person with lots of cash
4,942
5
2008-08-07T16:43:21Z
4,978
11
2008-08-07T17:04:25Z
[ "php", "python", "ruby-on-rails", "ruby" ]
When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?
This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to ...
How do you set up Python scripts to work in Apache 2.0?
5,102
14
2008-08-07T18:24:12Z
5,129
12
2008-08-07T18:40:53Z
[ "python", "apache", "apache2" ]
I tried to follow a couple of googled up tutorials on setting up mod\_python, but failed every time. Do you have a good, step-by step, rock-solid howto? My dev box is OS X, production - Centos.
There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons. Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (<http://httpd....
How do you set up Python scripts to work in Apache 2.0?
5,102
14
2008-08-07T18:24:12Z
5,165
8
2008-08-07T19:02:57Z
[ "python", "apache", "apache2" ]
I tried to follow a couple of googled up tutorials on setting up mod\_python, but failed every time. Do you have a good, step-by step, rock-solid howto? My dev box is OS X, production - Centos.
Yes, mod\_python is pretty confusing to set up. Here's how I did it. In httpd.conf: ``` LoadModule python_module modules/mod_python.so <Directory "/serverbase/htdocs/myapp"> AddHandler mod_python .py PythonHandler myapp PythonDebug On ``` and in your application directory: ``` $ /serverbase/htdocs/...
Cross Platform, Language Agnostic GUI Markup Language?
5,313
11
2008-08-07T21:07:24Z
5,319
8
2008-08-07T21:10:27Z
[ "python", "user-interface", "markup" ]
I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even bette...
erm.. HTML? (trying to be funny here... while we wait for real answers..)
Convert Bytes to Floating Point Numbers in Python
5,415
21
2008-08-07T22:24:27Z
5,435
13
2008-08-07T22:35:48Z
[ "python", "floating-point" ]
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
You'll want the [struct](https://docs.python.org/3.4/library/struct.html) package.
Convert Bytes to Floating Point Numbers in Python
5,415
21
2008-08-07T22:24:27Z
73,281
32
2008-09-16T14:59:37Z
[ "python", "floating-point" ]
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
``` >>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' ```
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
5,430
24
2008-08-07T22:32:23Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` ...
**Note:** This answer is sort of outdated (from 2008). Please use the solution below with care!! --- Here is a page that details the problem and a solution (search the page for the text *Wrapping sys.stdout into an instance*): [PrintFails - Python Wiki](http://wiki.python.org/moin/PrintFails) Here's a code excerpt ...
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
2,013,263
7
2010-01-06T13:38:39Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` ...
The below code will make Python output to console as UTF-8 even on Windows. The console will display the characters well on Windows 7 but on Windows XP it will not display them well, but at least it will work and most important you will have a consistent output from your script on all platforms. You'll be able to redi...
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
4,637,795
19
2011-01-09T05:07:56Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` ...
Despite the other plausible-sounding answers that suggest changing the code page to 65001, that [does not work](http://bugs.python.org/issue1602). (Also, changing the default encoding using `sys.setdefaultencoding` is [not a good idea](http://stackoverflow.com/questions/3578685/how-to-display-utf-8-in-windows-console/3...
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
10,667,978
10
2012-05-19T18:48:28Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` ...
If you're not interested in getting a reliable representation of the bad character(s) you might use something like this (working with python >= 2.6, including 3.x): ``` from __future__ import print_function import sys def safeprint(s): try: print(s) except UnicodeEncodeError: if sys.version_in...
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
32,176,732
13
2015-08-24T07:35:32Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` ...
**Update:** [Python 3.6](https://docs.python.org/3.6/whatsnew/3.6.html#pep-528-change-windows-console-encoding-to-utf-8) implements [PEP 528: Change Windows console encoding to UTF-8](https://www.python.org/dev/peps/pep-0528/): *the default console on Windows will now accept all Unicode characters.* Internally, it uses...
Get size of a file before downloading in Python
5,909
28
2008-08-08T13:35:19Z
5,935
16
2008-08-08T13:47:26Z
[ "python", "urllib" ]
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? ``` import urllib import re url = "http://www.someurl.com" # Download...
Using the returned-urllib-object method `info()`, you can get various information on the retrived document. Example of grabbing the current Google logo: ``` >>> import urllib >>> d = urllib.urlopen("http://www.google.co.uk/logos/olympics08_opening.gif") >>> print d.info() Content-Type: image/gif Last-Modifi...
Get size of a file before downloading in Python
5,909
28
2008-08-08T13:35:19Z
5,985
19
2008-08-08T14:21:51Z
[ "python", "urllib" ]
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? ``` import urllib import re url = "http://www.someurl.com" # Download...
I have reproduced what you are seeing: ``` import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "r") print "File on disk:",len(f.read()) f.close() ...
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
8,699
74
2008-08-12T11:40:13Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
The [lxml package](http://lxml.de/) supports xpath. It seems to work pretty well, although I've had some trouble with the self:: axis. There's also [Amara](http://pypi.python.org/pypi/Amara/1.1.6), but I haven't used it personally.
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
10,846
7
2008-08-14T09:48:59Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
The latest version of [elementtree](http://effbot.org/zone/element-xpath.htm) supports XPath pretty well. Not being an XPath expert I can't say for sure if the implementation is full but it has satisfied most of my needs when working in Python. I've also use lxml and PyXML and I find etree nice because it's a standard ...
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
27,974
106
2008-08-26T13:06:39Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
[libxml2](http://xmlsoft.org/python.html) has a number of advantages: 1. Compliance to the [spec](http://www.w3.org/TR/xpath) 2. Active development and a community participation 3. Speed. This is really a python wrapper around a C implementation. 4. Ubiquity. The libxml2 library is pervasive and thus well tested. Dow...
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
1,732,475
35
2009-11-13T23:11:17Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
Use LXML. LXML uses the full power of libxml2 and libxslt, but wraps them in more "Pythonic" bindings than the Python bindings that are native to those libraries. As such, it gets the full XPath 1.0 implementation. Native ElemenTree supports a limited subset of XPath, although it may be good enough for your needs.
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
2,122,709
23
2010-01-23T09:30:19Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
Another option is [py-dom-xpath](http://code.google.com/p/py-dom-xpath/), it works seamlessly with minidom and is pure Python so works on appengine. ``` import xpath xpath.find('//item', doc) ```
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
3,547,741
9
2010-08-23T13:00:01Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
You can use: **PyXML**: ``` from xml.dom.ext.reader import Sax2 from xml import xpath doc = Sax2.FromXmlFile('foo.xml').documentElement for url in xpath.Evaluate('//@Url', doc): print url.value ``` **libxml2**: ``` import libxml2 doc = libxml2.parseFile('foo.xml') for url in doc.xpathEval('//@Url'): print url.c...
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
13,504,511
30
2012-11-22T01:05:52Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
Sounds like an lxml advertisement in here. ;) ElementTree is included in the std library. Under 2.6 and below its xpath is pretty weak, but in [2.7 much improved](http://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support): ``` import xml.etree.ElementTree as ET root = ET.parse(filename) result = '' fo...
Accessing mp3 Meta-Data with Python
8,948
81
2008-08-12T15:16:00Z
9,358
11
2008-08-13T00:44:26Z
[ "python", "mp3", "metadata" ]
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
What you're after is the [ID3](http://id3-py.sourceforge.net/) module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following: ``` from ID3 import * try: id3info = ID3('file.mp3') print id3info # ...
Accessing mp3 Meta-Data with Python
8,948
81
2008-08-12T15:16:00Z
10,845
25
2008-08-14T09:46:21Z
[ "python", "mp3", "metadata" ]
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
I've used [mutagen](https://bitbucket.org/lazka/mutagen) to edit tags in media files before. The nice thing about mutagen is that it can handle other formats, such as mp4, FLAC etc. I've written several scripts with a lot of success using this API.
Accessing mp3 Meta-Data with Python
8,948
81
2008-08-12T15:16:00Z
102,285
75
2008-09-19T14:30:41Z
[ "python", "mp3", "metadata" ]
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
I used [eyeD3](http://eyed3.nicfit.net/) the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to download the tar and execute `python setup.py install` from the source folder. Relevant examples from the website are below. Readi...
Accessing mp3 Meta-Data with Python
8,948
81
2008-08-12T15:16:00Z
4,559,380
7
2010-12-30T01:40:52Z
[ "python", "mp3", "metadata" ]
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
check this one out: <https://github.com/Ciantic/songdetails> Usage example: ``` >>> import songdetails >>> song = songdetails.scan("data/song.mp3") >>> print song.duration 0:03:12 ``` Saving changes: ``` >>> import songdetails >>> song = songdetails.scan("data/commit.mp3") >>> song.artist = "Great artist" >>> song...
How do I treat an integer as an array of bytes in Python?
10,123
8
2008-08-13T17:46:41Z
10,129
10
2008-08-13T17:56:34Z
[ "python" ]
I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs: > a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the...
This will do what you want: ``` signum = status & 0xff exitstatus = (status & 0xff00) >> 8 ```
How do I treat an integer as an array of bytes in Python?
10,123
8
2008-08-13T17:46:41Z
10,213
10
2008-08-13T18:52:36Z
[ "python" ]
I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs: > a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the...
To answer your general question, you can use [bit manipulation](http://en.wikipedia.org/wiki/Bit_twiddling) techniques: ``` pid, status = os.wait() exitstatus, signum = status & 0xFF, (status & 0xFF00) >> 8 ``` However, there are also [built-in functions](http://docs.python.org/lib/os-process.html#l2h-2780) for inter...
How should I unit test a code-generator?
11,060
18
2008-08-14T13:59:21Z
11,074
8
2008-08-14T14:04:25Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions. I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When I developed...
I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look. Problem is, this is hard to test, the generated code might not be suited ...
Can you check that an exception is thrown with doctest in Python?
12,592
28
2008-08-15T18:43:17Z
12,609
45
2008-08-15T19:04:13Z
[ "python", "doctest" ]
Is it possible to write a doctest unit test that will check that an exception is raised? For example, if I have a function `foo(x)` that is supposed to raise an exception if `x<0`, how would I write the doctest for that?
Yes. You can do it. The [doctest module documentation](https://docs.python.org/3/library/doctest.html) and Wikipedia has an [example](http://en.wikipedia.org/wiki/Doctest#Example_2%3a_doctests_embedded_in_a_README.txt_file) of it. ``` >>> x Traceback (most recent call last): ... NameError: name 'x' is no...
Python version of PHP's stripslashes
13,454
9
2008-08-17T01:23:50Z
13,598
10
2008-08-17T12:15:13Z
[ "python", "string", "escaping" ]
I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes: ``` cleaned = stringwithslashes cleaned = cleaned.replace('\\n', '\n') cleaned = cleaned.replace('\\r', '\n') cleaned = cleaned.replace('\\', '') ``` How can I condense it?
Not totally sure this is what you want, but.. ``` cleaned = stringwithslashes.decode('string_escape') ```
Python Regular Expressions to implement string unescaping
13,791
10
2008-08-17T18:20:21Z
13,943
7
2008-08-17T21:36:32Z
[ "python", "regex", "backreference" ]
I'm trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what... ``` >>> import re >>> mystring = r"This is \n a test \r" >>> p = re.compile( "\\\\(\\S)" ) >>> p.sub( "\\1", mystring ) '...
Isn't that what [Anders' second example](#13844) does? In 2.5 there's also a `string-escape` encoding you can apply: ``` >>> mystring = r"This is \n a test \r" >>> mystring.decode('string-escape') 'This is \n a test \r' >>> print mystring.decode('string-escape') This is a test >>> ```
Can you explain closures (as they relate to Python)?
13,857
56
2008-08-17T19:14:30Z
13,875
37
2008-08-17T19:32:33Z
[ "python", "functional-programming", "closures" ]
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful: ``` >>> def makeConstantAdder(x): ... constant = x ... def adder(y): ... return y + constant ... return adder ... >>> f = makeConstantAdde...
Can you explain closures (as they relate to Python)?
13,857
56
2008-08-17T19:14:30Z
13,906
13
2008-08-17T20:25:18Z
[ "python", "functional-programming", "closures" ]
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
I like [this rough, succinct definition](http://effbot.org/zone/closure.htm): > A function that can refer to environments that are no longer active. I'd add > A closure allows you to bind variables into a function *without passing them as parameters*. Decorators which accept parameters are a common use for closures...
Can you explain closures (as they relate to Python)?
13,857
56
2008-08-17T19:14:30Z
24,061
11
2008-08-23T07:43:18Z
[ "python", "functional-programming", "closures" ]
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
To be honest, I understand closures perfectly well except I've never been clear about what exactly is the thing which is the "closure" and what's so "closure" about it. I recommend you give up looking for any logic behind the choice of term. Anyway, here's my explanation: ``` def foo(): x = 3 def bar(): p...
Can you explain closures (as they relate to Python)?
13,857
56
2008-08-17T19:14:30Z
141,426
60
2008-09-26T19:28:32Z
[ "python", "functional-programming", "closures" ]
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
[Closure on closures](http://mrevelle.blogspot.com/2006/10/closure-on-closures.html) > Objects are data with methods > attached, closures are functions with > data attached. ``` def make_counter(): i = 0 def counter(): # counter() is a closure nonlocal i i += 1 return i return coun...
Python Sound ("Bell")
13,941
34
2008-08-17T21:33:39Z
13,949
47
2008-08-17T21:46:02Z
[ "python", "osx", "audio", "terminal" ]
I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use `import os` and then use a command line speech program to say "Process complete." I much rather it be a simple "bell." I know that there's a function that can be used in Cocoa apps, NSBeep, but I don't th...
Have you tried : ``` import sys sys.stdout.write('\a') sys.stdout.flush() ``` That works for me here on Mac OS 10.5 Actually, I think your original attempt works also with a little modification: ``` print('\a') ``` (You just need the single quotes around the character sequence).
Python Sound ("Bell")
13,941
34
2008-08-17T21:33:39Z
34,482
9
2008-08-29T15:47:05Z
[ "python", "osx", "audio", "terminal" ]
I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use `import os` and then use a command line speech program to say "Process complete." I much rather it be a simple "bell." I know that there's a function that can be used in Cocoa apps, NSBeep, but I don't th...
If you have PyObjC (the Python - Objective-C bridge) installed or are running on OS X 10.5's system python (which ships with PyObjC), you can do ``` from AppKit import NSBeep NSBeep() ``` to play the system alert.
Is there a python module for regex matching in zip files
14,281
3
2008-08-18T07:41:09Z
14,320
8
2008-08-18T08:19:06Z
[ "python", "regex", "zip", "text-processing" ]
I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way...
There's nothing that will automatically do what you want. However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file. ``` #!/usr/bin/python import zipfile f = zipfile.ZipFile('myfile.zip') for subfile in f.namelist(): print subfile data = f.rea...
Regex and unicode
14,389
21
2008-08-18T09:41:14Z
14,391
14
2008-08-18T09:43:10Z
[ "python", "regex", "unicode", "character-properties" ]
I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi) The script works fine, that is until you try and use it on files that have Unicode show-names ...
Use a subrange of [\u0000-\uFFFF] for what you want. You can also use the re.UNICODE compile flag. [The docs](http://docs.python.org/lib/re-syntax.html) say that if UNICODE is set, \w will match the characters [0-9\_] plus whatever is classified as alphanumeric in the Unicode character properties database. See also <...
How do I validate xml against a DTD file in Python
15,798
27
2008-08-19T06:24:54Z
15,931
28
2008-08-19T09:39:56Z
[ "python", "xml", "validation", "dtd" ]
I need to validate an XML string (and not a file) against a DTD description file. How can that be done in `python`?
Another good option is [lxml's validation](http://lxml.de/validation.html) which I find quite pleasant to use. A simple example taken from the lxml site: ``` from StringIO import StringIO from lxml import etree dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>""")) root = etree.XML("<foo/>") print(dtd.validate(root)...
How do I validate xml against a DTD file in Python
15,798
27
2008-08-19T06:24:54Z
270,538
7
2008-11-06T22:17:48Z
[ "python", "xml", "validation", "dtd" ]
I need to validate an XML string (and not a file) against a DTD description file. How can that be done in `python`?
from the examples directory in the libxml2 python bindings: ``` #!/usr/bin/python -u import libxml2 import sys # Memory debug specific libxml2.debugMemory(1) dtd="""<!ELEMENT foo EMPTY>""" instance="""<?xml version="1.0"?> <foo></foo>""" dtd = libxml2.parseDTD(None, 'test.dtd') ctxt = libxml2.newValidCtxt() doc = l...
Prototyping with Python code before compiling
16,067
18
2008-08-19T12:32:38Z
28,467
10
2008-08-26T15:58:08Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually. IIRC, one of Python's original remits was as a prototyping langua...
I haven't used SWIG or SIP, but I find writing Python wrappers with [boost.python](http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html) to be very powerful and relatively easy to use. I'm not clear on what your requirements are for passing types between C/C++ and python, but you can do that easily by eithe...
Prototyping with Python code before compiling
16,067
18
2008-08-19T12:32:38Z
1,661,276
33
2009-11-02T13:16:20Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually. IIRC, one of Python's original remits was as a prototyping langua...
Finally a question that I can really put a value answer to :). I have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown: **Disclaimer**: This is my...